package com.qf.service.impl;

import com.qf.entity.SysPermission;
import com.qf.entity.SysRole;
import com.qf.entity.SysUser;
import com.qf.mapper.UserMapper;
import com.qf.service.IUserService;
import com.qf.utils.security.JwtUtils;
import com.qf.utils.security.RsaUtils;
import com.qf.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.security.PrivateKey;
import java.util.List;

/**
 * <p>title: com.qf.service.impl</p>
 * <p>Company: wendao</p>
 * author zhuximing
 * date 2021/9/23
 * description:
 */
@Service
public class UserService implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result login(SysUser user) {

        try {
            if (user == null) {
                return  new Result(false, "用户名或者密码不正确");
            }

            //根据用户名获取用户信息
            SysUser userFromDB = userMapper.findUserByName(user.getUserName());
            if (userFromDB == null) {
                return  new Result(false, "用户名或者密码不正确");
            }

            //校验密码
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(user.getPassword(), userFromDB.getPassword());
            if(!matches){
                return  new Result(false, "用户名或者密码不正确");
            }



            //获取用户的角色列表
            List<SysRole> roleList = userMapper.findRolesByUserId(userFromDB.getUserId());
            String roles = "";
            for (SysRole sysRole : roleList) {
                roles+= sysRole.getRoleName()+",";
            }
            userFromDB.setRoles(roles);

            //获取权限列表
            List<SysPermission> permissionList = userMapper.findPermissionByUserId(userFromDB.getUserId());

            String permissions = "";
            for (SysPermission sysPermission : permissionList) {
                permissions += sysPermission.getPermName()+",";
            }

            userFromDB.setPermission(permissions);
            userFromDB.setPassword("");

            //颁发令牌
            PrivateKey privateKey = RsaUtils.getPrivateKey(ResourceUtils.getFile("classpath:rsa_pri").getPath());

            String jwt = JwtUtils.generateTokenExpireInMinutes(userFromDB/*payload*/, privateKey, 1000);

            return new Result(true, "success",jwt);
        } catch (Exception exception) {
            exception.printStackTrace();
            return  new Result(false, "用户名或者密码不正确");
        }



    }
}